package com.freen.fadmin.controller.jwt.SysuserApi;

import com.alibaba.fastjson.JSON;
import com.freen.fadmin.controller.jwt.JwtSysuserBaseController;
import com.freen.fadmin.entity.sysuser.SysRole;
import com.freen.fadmin.entity.sysuser.SysUser;
import com.freen.fadmin.repository.sysuser.SysPermissionRepository;
import com.freen.fadmin.repository.sysuser.SysRoleRepository;
import com.freen.fadmin.repository.sysuser.SysUserRepository;
import com.freen.fadmin.util.JwtSysuserTokenUtils;
import com.freen.fadmin.util.OBJtoHashMap;
import com.freen.fadmin.util.result.ExceptionMsg;
import com.freen.fadmin.util.result.Response;
import com.freen.fadmin.util.result.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
public class MainController extends JwtSysuserBaseController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysPermissionRepository sysPermissionRepository;

    //反馈前端当前用户信息接口
    @ResponseBody
    @RequestMapping(value = "/SysApi/SysUser",method = RequestMethod.GET)
    //@PreAuthorize("principal.id.equals(#user_id)")
    public Response Sysuser(Principal principal){
        //Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = sysUserRepository.findByName(principal.getName());
        HashMap<String,Object> resSysUser;
        try {
            resSysUser = OBJtoHashMap.convertToMap(sysUser);
            resSysUser.remove("password");
            resSysUser.remove("roles");
            ArrayList <String> roles = new ArrayList<>();
            for (SysRole role:sysUser.getRoles()){
                String srole = role.getRole();
                String[] strs = srole.split("_");
                roles.add(strs[1]);
            }
            resSysUser.put("roles",roles);
        }catch (Exception e){
            return result();
        }
        
        return new ResponseData(ExceptionMsg.SUCCESS,resSysUser);
    }



    @ResponseBody
    @RequestMapping(value = "/SysApi/addSysUser/{username}/{password}",method = RequestMethod.GET)
    //@PreAuthorize("principal.id.equals(#user_id)")
    public Response addSysUser(@PathVariable String username, @PathVariable String password){
        //Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (username == null) return new ResponseData(ExceptionMsg.FAILED,"用户名不能为空");
        if (password == null) return new ResponseData(ExceptionMsg.FAILED,"密码不能为空");

        SysUser sysUser = sysUserRepository.findByName(username);
        if (null == sysUser) {
            sysUser = new SysUser();
            BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
            String encodePassword = encoder.encode(password);
            sysUser.setPhone("66");
            sysUser.setCnname("66");
            sysUser.setName(username);
            sysUser.setPassword(encodePassword);
//            sysUser.setRoles(); //控制台去补充设置
            sysUser.setEnabled(true);

            // 创建权限,这里给每个这样的用户,给一个 guest 的角色
            String rolestr = "ROLE_guest";
            SysRole role = sysRoleRepository.findByRole(rolestr);
            if (null == role) {
                role = new SysRole();
                role.setAvailable(true);
                role.setCnname("管理游客");
                role.setDescription("管理游客");
                role.setRole(rolestr);
                sysRoleRepository.save(role);
            }
            List<SysRole> roles = new ArrayList<>();
            roles.add(role);
            sysUser.setRoles(roles);


            //还需要ip 啊，什么的，暂时就不弄了。
            sysUserRepository.save(sysUser);
        }else{
            return new ResponseData(ExceptionMsg.FAILED,"已经有用户了");
        }


        return new ResponseData(ExceptionMsg.SUCCESS,"创建成功,请用该用户去登陆吧");
    }


    // 用户登出操作
    @ResponseBody
    @RequestMapping(value = "/SysApi/Logout",method = RequestMethod.GET)
    public Response Logout(HttpServletRequest request){
        String tokenHeader = request.getHeader(JwtSysuserTokenUtils.TOKEN_HEADER);
        String token = tokenHeader.replace(JwtSysuserTokenUtils.TOKEN_PREFIX,"");
        ServletContext context = request.getServletContext();
        context.removeAttribute(token);
        return result(ExceptionMsg.SUCCESS);
    }

}
